import React, { useState } from 'react';;
import {
    EditableProTable,
    ProForm,
    ProFormText, ProTable,
} from '@ant-design/pro-components';
import {Modal, Space, Upload} from "antd";
import Decimal from "decimal.js";
import TheButton from "@/components/TheButton/index.jsx";
import {apiAppCouponInfoPage} from "@/api/couponManagement/timeTask.jsx";
const CouponList = (props) => {
    const selectKeys = props.value.map((item) => item.couponId);
    const [editableKeys, setEditableRowKeys] = useState(() =>
        props.value.map((item) => item.couponId),
    );
    // console.log(props)
    const [dataSource, setDataSource] = useState(props.value || []);
    const [selectedRows, setSelectedRows] = useState([]);
    const [modalOpen, setModalOpen] = useState(false);
    // const [tableProps, setTableProps] = useState(false);
    const columns = [
        {
            title: '优惠券id',
            dataIndex: 'couponId',
            key: 'couponId',
            editable: false,
            // valueType: 'digit',
            // fieldProps: { precision: 0, stringMode: true},
            // formItemProps: {
            //     rules: [
            //         {
            //             pattern: /^[1-9]*[1-9][0-9]*$/,
            //             message: '只允许输入非0开始的数字',
            //         },
            //     ],
            // },
        },
        {
            title: '优惠券名称',
            dataIndex: 'couponTitle',
            key: 'couponTitle',
            editable: false
        },
        {
            title: '优惠券类型',
            dataIndex: 'couponType',
            key: 'couponType',
            editable: false,
            hideInSearch: true,
            valueEnum: {
                'J': { text: '代金券' },
                'Z': { text: '折扣券' },
            },
        },
        {
            title: '范围',
            dataIndex: 'commodityScope',
            key: 'commodityScope',
            editable: false,
            hideInSearch: true,
            valueEnum: {
                0: { text: '全部商品可用' },
                1: { text: '限制品类可用' },
                2: { text: '商品券' },
            },
        },
        {
            title: '优惠',
            dataIndex: "couponPrice",
            key: "couponPrice",
            editable: false,
            hideInSearch: true,
            render: (text, render) => {
                let label = ''
                switch (render.couponType) {
                    case 'J':
                        label = "减免"+Decimal(text).div(Decimal(100)).toNumber()+"元"
                        break;
                    case 'Z':
                        label = "打"+Decimal(text).div(Decimal(10)).toNumber()+"折"
                        if (render.couponMaxPrice !== -1){
                            label+= ',最大折扣金额'+Decimal(render.couponMaxPrice).div(Decimal(100)).toNumber()+'元'
                        }
                        break;
                    default:
                        label = "字段值错误"
                }
                return label
            }
        },
        {
            title: '状态',
            dataIndex: "activeStatus",
            key: "activeStatus",
            editable: false,
            hideInSearch: true,
            valueEnum: {
                0: { text: '未开始',status: 'Default' },
                1: { text: '进行中',status: 'Processing' },
                2: { text: '已结束',status: 'Success' },
            },
        },
        {
            title: '最近修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            valueType: 'dateTime',
            editable: false,
            hideInSearch: true,
            width: 250
        },

    ]
    let tableProps = {}
    if (props.mode === 'view'){
        tableProps = {
            toolBarRender: false
        }
    }
    else {
        tableProps = {
            toolBarRender: (action) => {
                return action.toolBarRender
            }
        }
    }
    return <>
        <EditableProTable
            rowKey="couponId"
            bordered={true}
            cardBordered={true}
            scroll={{y: '500px'}}
            {...tableProps}
            headerTitle={
                <TheButton
                    key="new"
                    onClick={() => {
                        setModalOpen(true)
                    }}
                >
                    选择优惠券
                </TheButton>
            }
            columns={[...columns,{
                title: '操作',
                valueType: 'option',
                width: 250,
                fixed: "right",
                hideInTable: props.mode === 'view',
                render: () => {
                    return null;
                },
            }]}
            recordCreatorProps={false}
            value={dataSource}
            controlled={true}
            onChange={props.onValuesChange}
            editable={{
                type: 'multiple',
                editableKeys,
                onChange: setEditableRowKeys,
                actionRender: (row, _, dom) => {
                    return <Space style={{margin:"0 auto"}}>{[dom.delete]}</Space>;
                },
                onValuesChange: (record, recordList) => {
                    setDataSource(recordList);
                },
            }}
            pagination={{
                defaultPageSize: 5
            }}
        />
        <Modal
            title={'选择优惠券'}
            width={'80%'}
            open={modalOpen}
            destroyOnClose={true}
            onOk={() => {
                setDataSource(selectedRows)
                setEditableRowKeys(selectedRows.map((item) => item.couponId))
                props.onValuesChange(selectedRows)
                setModalOpen(false)
            }}
            onCancel={() => setModalOpen(false)}
        >
            <ProTable
                bordered={true}
                options={false}
                scroll={{x: "max-content", y: '57vh'}}
                rowKey={(record) => record.couponId}
                columns={columns}
                params={{
                    activeStatus: 1,
                    over: 1,
                }}
                request={async (params, sort, filter) => {
                    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
                    // 如果需要转化参数可以在这里进行修改
                    const res = await apiAppCouponInfoPage({
                        pageNo: params.current,
                        pageSize: params.pageSize,
                        ...params
                    });
                    return {
                        data: res.rows,
                        // success 请返回 true，
                        // 不然 table 会停止解析数据，即使有数据
                        success: res.code === 0,
                        // 不传会使用 data 的长度，如果是分页一定要传
                        total: res.totalCount,
                    };
                }}
                pagination={{
                    defaultPageSize: 10
                }}
                rowSelection={{
                    defaultSelectedRowKeys: selectKeys,
                    preserveSelectedRowKeys: true,
                    onChange: (keys, rows) => {
                      setSelectedRows((prev) => {
                          let arr = []
                          rows.forEach((item,index)=>{
                              if (item === undefined){
                                  arr.push(prev.find(v=>v.couponId === keys[index]))
                              }
                              else{
                                  arr.push(item)
                              }
                          })
                          return arr;
                      });
                  }
                }}
                search={{
                    optionRender: (searchConfig,formProps,dom)=>{
                        return dom.reverse()
                    }
                }}
            />
        </Modal>
    </>
};

export default CouponList;
